import './index.css';
// 计算器
import { useState, useEffect, useRef } from 'react';
import { Switch, Route, Link, HashRouter as Router } from "react-router-dom";
// import Calculator from './Calulator';
import TailWindCard from './TailWindCard';
import CardList from '../pages/card';
import Table from './Table';
import Demo from '../pages/Login/index.tsx'
import { keyframes } from 'styled-components';
import axios from 'axios';

import XLSX from 'xlsx';

export const transformExcel = (f: any) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e: any) => {
      let data: any = [];
      const { result } = e.target;
      try {
        // 以二进制流读取整份Excel表格对象
        const workbook = XLSX.read(result, { type: 'binary' });
        console.log('return1');
        // 遍历工作表进行读取（默认是第一张表）
        for (const sheet in workbook.Sheets) {
          if (workbook?.Sheets?.hasOwnProperty(sheet)) {
            // 处理好的数据
            data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]))
          }
        }
      } catch (err) {
        console.log('return2', result);
        // Message.error('文件类型不正确')
        return
      }
      // 最终的结果
      resolve(data)
    }
    // 以二进制的方式打开
    reader.readAsBinaryString(f);
  })
}


import { InboxOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { message, Upload } from 'antd';
const { Dragger } = Upload;

const dealFile = async (e: any) => {
  console.log(e, 'before');
  const data = await transformExcel(e);
  console.log(data, 'data');

}

const props: UploadProps = {
  name: 'file',
  multiple: true,
  action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  beforeUpload(e) {
    dealFile(e);
  },
  // onChange(info) {
  //   const { status } = info.file;
  //   if (status !== 'uploading') {
  //     console.log(info.file, info.fileList);
  //   }
  //   if (status === 'done') {
  //     message.success(`${info.file.name} file uploaded successfully.`);
  //   } else if (status === 'error') {
  //     message.error(`${info.file.name} file upload failed.`);
  //   }
  // },
  onDrop(e) {
    console.log('Dropped files', e.dataTransfer.files);
  },
};
const cardDataList: any = [
  {
    title: '杭州市通用5元券',
    subTitle: '杭味面馆非常好吃，太好吃了，相当不错，味道鲜美，特别划算，快快抢购，聚划算',
  },
  {
    title: '杭州市10元券',
    subTitle: '兰州拉面非常好吃',
  },
];

// import Demo from './Login';

export default function IndexPage() {
  // const contorller  = new AbortController;
  // contorller.abort();
  const [searchText, setsearchText] = useState<string>('');
  const [data, setData] = useState<any[]>([]);

  const getData = async (e: any) => {
    console.log(e.key);
    if (e.key === 'Enter') {
      setData(cardDataList);
      // axios.get('/api/data');
    }
  }
  const onChange = (e: any) => {
    const { value } = e.target;
    setsearchText(value);
  }

  // console.log(document.styleSheets)//获取页面所有的style标签  StyleSheetList{0:CSSStyleSheet,1:CSSStyleSheet,length:2}
  // console.log(document.styleSheets[0])//第一个style标签 CSSStyleSheet{...}
  // console.log(document.styleSheets[0].cssRules)//~的所有选择器css列表；CSSRuleList{0:CSSStyleRule,1:CSSStyleRule,length:2}
  // console.log(document.styleSheets[0].cssRules[0])//CSSStyleRule {selectorText: ".box"...box
  // console.log(document.styleSheets[0].cssRules[0].cssText)//就是".box { width: 100px; height: 100px; background-color: red; }"
  // console.log(document.styleSheets[0].cssRules[0].selectorText)// .box 
  // console.log(document.styleSheets[0].cssRules[0].style)//就是CSSStyleDeclaration
  // console.log(document.styleSheets[0].cssRules[0].style.width) //100px
  // document.styleSheets[0].cssRules[2].style.backgroundColor = 'black';//样式会作用上去?
  //两者都可以添加css样式到styleSheets样式表中，不是加载style中；
  //styleSheet.insertRule("选择器{样式内容}",插入在第几个选择器索引)

  // document.styleSheets[0].addRule(".div","width:100px;border:1px solid red",document.styleSheets[0].cssRules.length) 
  //styleSheet.insertRule("选择器","css样式",插入在第几个选择器索引)
  //早期浏览器不支持
  const [dat, setDat] = useState(1);
  //  document.styleSheets[0].insertRule(".animateR{width:100px;height:100px;background-color:blue",document.styleSheets[0].cssRules.length)

  useEffect(() => {
    const color = ["green", "blue", "yellow"]
    var styleSheets = document.styleSheets[0];  //获取样式表引用
    var index = styleSheets.length;
    document.querySelector(".animateR").style = `
            animation: move_${1} ${1}s linear forwards;
            width:${Math.floor(Math.random() * 300)}px;
            background-color:${color[Math.floor(Math.random() * 3)]}
    `
    styleSheets.insertRule(`@keyframes move_${1}
        {
            from {
                transform: translateX(${Math.floor(0)}px);
            }
            to {
                transform: translateX(${Math.floor(Math.random() * 300)}px);
            }
      }`, index);
    setTimeout(() => {
      styleSheets.deleteRule(index);
    }, 1000);

    // console.log(color[Math.floor(Math.random()*3)]);
    // document.querySelector(".animateR").style.color=color[Math.floor(Math.random()*3)];
  }, [dat])

  // document.styleSheets[0].insertRule(`@keyframes move_1
  //  {
  //      from {
  //          transform: translateX(${100}px);
  //      }
  //      to {
  //          transform: translateX(${100}px);
  //      }
  //  }`, document.styleSheets[0].cssRules.length)
  const first = useRef({
    a: 1,
    b: [1, 2, 3]
  })
 
  return (
    <div>
      {/* <Calculator /> */}
      {/* <CardList list={cardDataList} /> */}
      {/* <TailWindCard /> */}
      {/* <Table /> */}
      <input onKeyDown={getData} value={searchText} onChange={onChange} />
      {data.map((i) => {
        return i.title + "----"
      })}


      {/* <Router>
        <Link to="/aa">TailWindCard</Link>
        <Link to="/detail">Table</Link>
        <Switch>
          <Route path={'/aa'} exact component={TailWindCard}></Route>
          <Route path={'/detail'} component={Demo}></Route>
        </Switch>
      </Router> */}
      <Demo refDemo={first} />
      <Demo11 refDemo={first} />
      <Dragger {...props}>
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">Click or drag file to this area to upload</p>
        <p className="ant-upload-hint">
          Support for a single or bulk upload. Strictly prohibit from uploading company data or other
          band files
        </p>
      </Dragger>
      <div className="animateBg"></div>
      <div className="animateR" onClick={
        () => {
          console.log(11);
          // document.styleSheets[0].deleteRule(document.styleSheets[0].cssRules.length-1);
          setDat(dat + 1)
        }
      }>{dat}</div>
      <div onClick={() => {
      }} className="box">----</div>
    </div>
  );
}


function Demo11({ refDemo }:any) {
  const a=10
  return (
    <div onClick={() => {
      refDemo.current = {
        ...refDemo.current,
        a
      }
      console.log(refDemo.current, 'refDemo.current22');

    }}>index++++</div>
  )
}
